package com.ebrothers.isns.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.ebrothers.isns.vo.Location;
import com.google.android.maps.GeoPoint;

public final class Utils {
	private static final String TAG = "Utils";
	private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public static String dateToString(Date date) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_PATTERN);
		return format.format(date);
	}

	public static Date stringToDate(String date) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_PATTERN);
		return format.parse(date);
	}

	public static Location stringToLocation(String location) {
		Location loc = null;
		if (location != null && location.contains(":")) {
			String[] splits = location.split(":");
			if (splits.length == 2) {
				loc = new Location();
				loc.longitude = splits[0];
				loc.latitude = splits[1];
			}
		}
		return loc;
	}

	public static String locationToString(Location loc) {
		return encode(loc.name) + ":" + loc.longitude + "," + loc.latitude;
	}

	public static GeoPoint locationToGeoPoint(android.location.Location location) {
		Double lat = location.getLatitude() * 1e6;
		Double lng = location.getLongitude() * 1e6;
		return new GeoPoint(lat.intValue(), lng.intValue());
	}

	public static boolean isNetworkAvaliable(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] anetworkinfo = connManager.getAllNetworkInfo();
		for (int i = 0; i < anetworkinfo.length; i++) {
			if (anetworkinfo[i] != null && anetworkinfo[i].isConnected()) {
				return true;
			}
		}
		return false;
	}

	public static String encode(String text) {
		try {
			return URLEncoder.encode(text, "gbk");
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "******* Got an error:", e);
		}
		return null;
	}
}
